#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/9/25  20:37
# @Author: 余浪人
# @email: yulangren520@gmail.com

import IPy, json
from apps.control import sys_bp
from flask import jsonify, request, render_template
from apps.lib.public import redis_
from apps.jinja2 import ipAddress
from flask_login import login_required


# IP 访问频率中心
@sys_bp.route('/ip_frequency', endpoint='ipFrequency', methods=['GET', 'DELETE', 'EDIT'])
@login_required
def ipFrequency():
    redis_2 = redis_(2)
    if request.method == 'DELETE':
        redis_2.delete(request.form.get('uid', ''))
        redis_2.close()
        return jsonify({"status": 0, 'msg': "删除成功"})
    elif request.method == 'EDIT':
        redis_4 = redis_(4)
        IP = request.form.get('data', '')
        raw_data = redis_2.get(IP)
        if raw_data:
            data = json.loads(raw_data)
            data['address'] = ipAddress(IP)
            redis_2.delete(IP)
        else:
            data = {"IP": IP, "address": ipAddress(IP)}
        redis_4.set(IP, json.dumps(data))
        redis_2.close()
        redis_4.close()
        return jsonify({"status": 0, 'msg': "添加成功"})
    keys = redis_2.keys()
    dataList = []
    for k in keys:
        val = redis_2.get(k)
        if val and redis_2.ttl(k) >= 3:
            dataList.append(json.loads(val))
    redis_2.close()
    return render_template('system_template/ipFrequency_list.html', data_list=dataList)


# 禁止访问
@sys_bp.route('/ipForbid', endpoint='ipForbid', methods=['GET', 'DELETE', 'POST'])
@login_required
def ipForbid():
    redis_4 = redis_(4)
    if request.method == 'DELETE':
        redis_4.hdel('forbid_ip', request.form.get('data'))
        redis_4.close()
        return jsonify({"status": 0, 'msg': "移出成功"})
    elif request.method == 'POST':
        address = request.form.get('data')
        try:
            IPy.IP(address)
            redis_4.hset('forbid_ip', address, json.dumps({"IP": address, "address": ipAddress(address)}))
        except:
            redis_4.close()
            return jsonify({"status": 1, 'msg': "请输入合法IP地址"})
        redis_4.close()
        return jsonify({"status": 0, 'msg': "添加成功"})
    dataList = [json.loads(redis_4.hget('forbid_ip', k)) for k in redis_4.hkeys('forbid_ip')[::-1][:50]]
    redis_4.close()
    return render_template('system_template/ipForbid_list.html', data_list=dataList)


# IP冻结列表
@sys_bp.route('/ipFrozen', endpoint='ipFrozen', methods=['GET', 'POST', 'DELETE'])
def ipFrozen():
    r_3 = redis_(3)
    if request.method == 'POST':
        r_4 = redis_(4)
        IP = request.form.get('data')
        try:
            IPy.IP(IP)
            res = r_4.hset('forbid_ip', IP, json.dumps({"IP": IP, "address": ipAddress(IP)}))
            if res: r_3.delete(IP)
        except:
            r_3.close()
            r_4.close()
            return jsonify({"status": 1, 'msg': "请输入合法IP地址"})
        r_3.close()
        r_4.close()
        return jsonify({"status": 0, 'msg': "添加成功"})
    elif request.method == 'DELETE':
        IP = request.form.get('data')
        try:
            IPy.IP(IP)
            r_3.delete(IP)
        except:
            r_3.close()
            return jsonify({"status": 1, 'msg': "请输入合法IP地址"})
        return jsonify({"status": 0, 'msg': "解除限制成功"})
    keys = r_3.keys()
    dataList = [{"IP": json.loads(r_3.get(k))} for k in keys]
    r_3.close()
    return render_template('system_template/ipFrozen_list.html', data_list=dataList)
